<template>
    <el-form-item :label="label" :prop="prop" :rules="rules">
        <el-select v-model="selectedUnitId" :disabled="disabled" filterable remote clearable reserve-keyword
            :remote-method="remoteSearch" :loading="loading" :placeholder="placeholder" @change="handleUnitChange">
            <el-option v-for="unit in options" :key="unit.id" :label="unit.name" :value="unit.id" />
        </el-select>
    </el-form-item>
</template>

<script>
import { ElMessage } from 'element-plus'
import { DataPage } from '../../network/communicationConverter'
import { Definition } from '../../engine/common/definition'

export default {
    name: 'UnitSelect',
    props: {
        modelValue: {
            type: Object,
            default: null
        },
        label: {
            type: String,
            default: '单位'
        },
        prop: {
            type: String,
            default: 'unit'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: '请输入关键词搜索单位'
        },
        rules: {
            type: Array,
            default: () => []
        },
        basicUiAction: {
            type: Object,
            required: true
        }
    },
    emits: ['update:modelValue', 'change'],
    data() {
        return {
            selectedUnitId: '', // 初始化为 ID（而不是对象）
            options: [],
            loading: false,
            lastQuery: ''
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.selectedUnitId = val.id; // 更新 selectedUnitId 为 ID
                }
            }
        }
    },
    methods: {
        async remoteSearch(query) {
            if (query === this.lastQuery) return
            if (!this.basicUiAction) return
            this.lastQuery = query
            this.loading = true
            try {
                const res = await this.basicUiAction.getCommodityUnit(
                    new DataPage(1, 0, Definition.gDefualPageSize),
                    { lke_name: query }
                )
                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList
                }
            } catch (error) {
                console.error('搜索分类失败:', error)
                ElMessage.error('搜索分类失败')
            } finally {
                this.loading = false
            }
        },

        handleUnitChange(val) {
            // 根据选中的 ID，找到对应的完整对象
            const selectedUnit = this.options.find(u => u.id === val)
            if (selectedUnit) {
                // 更新 `commodity.unit` 为完整对象
                this.$emit('update:modelValue', selectedUnit)
                this.$emit('change', selectedUnit)
            }
        },

        async loadDefaultOptions() {
            if (!this.basicUiAction) return
            this.loading = true
            try {
                const res = await this.basicUiAction.getCommodityUnit(
                    new DataPage(1, 0, Definition.gDefualPageSize)
                )
                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList
                }
            } catch (error) {
                console.error('加载分类失败:', error)
            } finally {
                this.loading = false
            }
        }
    },
    mounted() {
        this.loadDefaultOptions()
    }
}
</script>
